package com.totoro.controller;

import com.totoro.pojo.*;
import com.totoro.service.ChatService;
import com.totoro.service.SellerService;
import com.totoro.service.ShopService;
import com.totoro.utils.ReturnFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author TOTORO
 * @date 2021/8/27 19:19
 * 聊天控制器设计
 */
@Controller
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    ChatService chatService;
    @Autowired
    SellerService sellerService;
    @Autowired
    ShopService shopService;

    /**
     * 通过阿里旺旺进入聊天面板之前的方法
     * @param toUid 接收者id，通常就是阿里旺旺的某个卖家
     * @param session
     * @return
     */
    @RequestMapping("/beforeAliOpenChatDialog")
    @ResponseBody
    public String beforeAliOpenChatDialog(@RequestParam("toUid") int toUid, HttpSession session){
        User user = (User) session.getAttribute("user");
        // 当前拿到的toUid可能是卖家id，首先通过卖家id获取用户id
        User finalUser = sellerService.findUserBySlid(toUid);
        int userId = toUid;
        if(finalUser != null){
            userId = finalUser.getUserId();
        }
        // 先判断是否有该聊天面板
        SuMainChat suMainChat = chatService.findAssignChatMain(user.getUserId(), userId);
        if(null !=suMainChat){
            // 查询用户再此次聊天面板中是发送者还是接收者
            int sender = 0;
            SuMainChat sendPosition = chatService.findUserSendPosition(user.getUserId(), suMainChat.getId());
            // 如果不为空，则是发送方，否则为接受方
            if(null == sendPosition){
                sender = 1;
            }
            // 如果有该聊天面板和发送位置，则取消该用户对此次聊天面板的删除状态 （不管有没有删除都执行一次）
            chatService.updateMainChatStatus(sender, suMainChat.getId(), 0);
            // 将这次的接收者id存进session，方便打开时直接拿
            session.setAttribute("toUid", userId);
            return ReturnFormat.retData("update", true);
        }

        // 如果没有该聊天面板，则生成一个新的
        SuMainChat newSuMainChat = new SuMainChat();
        newSuMainChat.setFromUid(user.getUserId());
        newSuMainChat.setToUid(userId);
        chatService.addMainChat(newSuMainChat);
        // 将这次的接收者id存进session，方便打开时直接拿
        session.setAttribute("toUid", userId);
        return ReturnFormat.retData("insert", true);
    }

    /**
     * 返回至聊天页面
     * @param session
     * 打开聊天框的方式有两种，第一种是通过指定阿里旺旺卖家打开 <> 第二种是随意打开，一开始就可以随意选择聊天用户
     * 所以通过阿里旺旺打开的时候需要将这次阿里旺旺卖家的聊天框排在第一，方便直接拿初始(第一条)聊天记录展示给用户看
     * @return
     */
    @RequestMapping("/openChatDialog")
    public String openChatDialog(HttpSession session, Model model){
        // 判断接收者id是否为空
        int toUid = 0;
        if(session.getAttribute("toUid") !=null){
            toUid = (int) session.getAttribute("toUid");
            System.out.println("接收者："+toUid);
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            return "empty";
        }
        // 获得此次打开聊天框的id
        SuMainChat suMainChat = chatService.findAssignChatMain(user.getUserId(), toUid);
        // 获得此次用户的所有左侧可选聊天框
        List<SuMainChat> suMainChats = chatService.findUserAllMainChat(user.getUserId(), false, toUid);
        if(suMainChats.size() < 1){
            model.addAttribute("suMainChats", new ArrayList<SuMainChat>());
            model.addAttribute("viceChatMap", new HashMap<String, List<SuViceChat>>());
            model.addAttribute("user", user);
            model.addAttribute("toIsSeller", false);
            model.addAttribute("shopRecommendProducts", new ArrayList<Product>());
            System.out.println("嗲无较大误差");
            return "buy_chat";
        }
        // 判断这次打开者是发送者还是接收者
        int sender = 0;
        SuMainChat checkSenderPosition = chatService.findUserSendPosition(user.getUserId(), suMainChats.get(0).getId());
        // 空，代表本次打开者是接收者，那么对方就是发送者，反之
        if(null == checkSenderPosition){
            sender = 1;
        }
        // 默认消息框肯定是排在第一条的聊天框，所以获取第一条聊天框里的对方在线状态
        // 如果左侧聊天框为空，则不展示任何记录
        if(suMainChats.size() < 1){
            model.addAttribute("suMainChats", new ArrayList<SuMainChat>());
            model.addAttribute("viceChatMap", new HashMap<String, List<SuViceChat>>());
            return "buy_chat";
        }
        // 将本次打开者的默认第一条聊天栏未读全部变成已读
        chatService.updateViceChatReadStatus(sender, suMainChats.get(0).getId());
        // 将这次聊天栏的第一条变为默认展示的聊天记录
        Map<String, List<SuViceChat>> viceChatMap = chatService.findMainChatDownAllChat(suMainChats.get(0).getId());
        // 存进数据模型中，返回到聊天页面进行首次数据渲染，之后的数据交给ajax
        model.addAttribute("suMainChats", suMainChats);
        model.addAttribute("viceChatMap", viceChatMap);
        model.addAttribute("user", user);
        // 通过toUid获得对方是否是店铺，店铺里是否有推荐商品
        boolean toIsSeller = false;
        Seller seller = sellerService.findSellerIdByUserId(toUid);
        List<Product> shopRecommendProducts = new ArrayList<Product>();
        if(null != seller){
            toIsSeller = true;
            Shop shop = shopService.findShopBySlid(seller.getId());
            shopRecommendProducts = shopService.findTermDescProduct(shop.getId(), "t2.deal_count desc");
            if(shopRecommendProducts.size() > 2){
                shopRecommendProducts = shopRecommendProducts.subList(0, 2);
            }
        }
        model.addAttribute("toIsSeller", toIsSeller);
        model.addAttribute("shopRecommendProducts", shopRecommendProducts);
        return "buy_chat";
    }

    /**
     * 变为已读
     * @param suMainChatId
     * @param session
     * @return
     */
    @RequestMapping("/alreadyReadChat")
    @ResponseBody
    public String alreadyReadChat(@RequestParam("suMainChatId") int suMainChatId, HttpSession session){
        User user = (User) session.getAttribute("user");
        int sender = 0;
        SuMainChat checkSenderPosition = chatService.findUserSendPosition(user.getUserId(), suMainChatId);
        // 空，代表本次打开者是接收者，那么对方就是发送者，反之
        if(null == checkSenderPosition){
            sender = 1;
        }
        chatService.updateViceChatReadStatus(sender, suMainChatId);
        return ReturnFormat.retData("success", true);
    }

    @RequestMapping(value = "/getMainChatDownChatContent", method = RequestMethod.POST)
    @ResponseBody
    public String getMainChatDownChatContent(@RequestParam("suMainChatId") int suMainChatId){
        Map<String, List<SuViceChat>> viceChatMap = chatService.findMainChatDownAllChat(suMainChatId);
        return ReturnFormat.retData(viceChatMap, true);
    }

    @RequestMapping("/selfShopRecommend")
    @ResponseBody
    public String selfShopRecommend(@RequestParam("sid") int sid){
        List<Product> dealDescProducts = shopService.findTermDescProduct(sid, "t2.deal_count desc");
        return ReturnFormat.retData(dealDescProducts.subList(0,2), true);
    }

    /**
     * 发送图片文件
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/sendChatImage")
    @ResponseBody
    public String sendChatImage(@RequestParam("file")MultipartFile file, HttpServletRequest request) throws IOException {
        if(file.getSize() < 4*1024*1024){
            return ReturnFormat.retData("文件大小于4M", false);
        }
        String uploadPath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\chat_image\\";
        File path =  new File(uploadPath);
        if(path == null){ path.mkdirs();}
        String ext =  file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if(".jpg.png.jpeg.gif".indexOf(ext) == -1){
            return ReturnFormat.retData("文件后缀名不符合要求", false);
        }
        String filename = UUID.randomUUID().toString();
        file.transferTo(new File(uploadPath+filename+file.getOriginalFilename()));
        return ReturnFormat.retData("发送成功", true);
    }
}
